<template>
  <div>
    <br>
    <!--搜索栏开始-->
    <el-row>
      <el-col :span="20" align="left">
        <el-form ref="searchParamsForm" :inline="true" size="small" class="demo-form-inline">
          <svg-icon icon-class="search" style="font-size: 25px;margin-left:20px;margin-top: 6px"></svg-icon>&nbsp;
          <el-form-item>
            <el-autocomplete v-model="mobile" :fetch-suggestions="mobileFetch" placeholder="手机号"></el-autocomplete>
          </el-form-item>
          <el-form-item>
            <el-autocomplete v-model="email" :fetch-suggestions="EmailFetch" placeholder="邮箱"></el-autocomplete>
          </el-form-item>
          <el-form-item>
            <el-select v-model="enable" style="width: 130px" placeholder="教师状态">
              <el-option label="禁用" :value="0"/>
              <el-option label="正常" :value="1"/>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" v-waves @click="btnQuery">查询</el-button>
            <el-button size="small" v-waves @click="resetSearch('searchParamsForm')">重置</el-button>
          </el-form-item>
        </el-form>
        <div style="margin-bottom: 12px;margin-left: 20px;">
          <el-button type="primary" size="small" icon="el-icon-plus" @click="addAuthority">添加教师</el-button>
          <el-button v-waves size="small" icon="el-icon-download" @click="exportToExcel">下载</el-button>
        </div>
      </el-col>
      <el-col :span="4" align="center">
        <el-button-group>
        </el-button-group>
      </el-col>
    </el-row>
    <!--搜索栏结束-->
    <!-- 教师列表 开始-->

    <el-row>
      <el-col :span="24" align="center">

        <div class="app-container">
          <el-table
            id="teacherTable"
            v-loading="loading"
            class="table"
            :data="teacherList"
            :cell-style="{ textAlign: 'center' }"
            :header-cell-style="{textAlign:'center'}"
          >
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="name" label="教师名称"></el-table-column>
            <el-table-column prop="mobile" header-align="left" label="联系方式"></el-table-column>
            <el-table-column prop="email" header-align="right" label="邮箱地址"></el-table-column>
            <el-table-column prop="createTime" label="注册时间"></el-table-column>
            <el-table-column prop="enable" width="100" label="状态">
              <template slot-scope="scope">
                <el-tag effect="plain" type="danger" v-waves v-if="scope.row.enable===0">禁用</el-tag>
                <el-tag effect="plain" type="primary" v-waves v-if="scope.row.enable===1">正常</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right">
              <template slot-scope="scope">
                <el-button type="primary" v-waves size="mini" @click="openUpdateProfileDialog(scope.$index)">修改</el-button>
                <el-button type="success" v-waves size="mini" @click="passwordAuthority(scope.$index)">改密</el-button>

                <el-popconfirm
                  style="margin-left: 10px"
                  placement="top-end"
                  confirm-button-text="确定"
                  cancel-button-text="取消"
                  icon="el-icon-info"
                  icon-color="red"
                  :title="`你要禁用[${scope.row.name}]吗？`"
                  @confirm="disableAuthority(scope.$index)"
                >
                  <el-button v-if="scope.row.enable===1" slot="reference" type="danger" size="mini">禁用</el-button>
                </el-popconfirm>
                <el-popconfirm
                  placement="top-end"
                  confirm-button-text="确定"
                  cancel-button-text="取消"
                  icon="el-icon-info"
                  icon-color="red"
                  :title="`你要启用[${scope.row.name}]吗？`"
                  @confirm="enableAuthority(scope.$index)"
                >
                  <el-button v-if="scope.row.enable===0" slot="reference" type="warning" size="mini">启用</el-button>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-col>
    </el-row>
    <br>
    <el-row>
      <el-col :span="24">
        <el-pagination
          background
          align="center"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="pageNum"
          :page-sizes="[10,15]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </el-col>
    </el-row>
    <!-- 教师列表 结束-->
    <div>
      <!-- 修改密码对话框 -->
      <el-dialog
        :title.sync="updatePasswordDialogTitle"
        :visible.sync="updatePasswordDialogVisible"
        destroy-on-close
        width="24%"
        @closed="()=>{newPassword=''}"
      >
        <el-input v-model="newPassword" size="small" autocomplete="off" placeholder="请输入账户新密码"/>
        <span slot="footer">
          <el-button type="primary" size="small" @click="updatePassword">更 新</el-button>
          <el-button size="small" @click="updatePasswordDialogVisible = false">取 消</el-button>
        </span>
      </el-dialog>
      <!-- 修改账户信息 -->
      <el-dialog
        :title.sync="updateProfileDialogTitle"
        :visible.sync="updateProfileDialogVisible"
        destroy-on-close
      >
        <v-teacher-add-update ref="UpdateDialog"/>
        <span slot="footer">
          <el-button type="primary" size="small" @click="updateAuthority">更 新</el-button>
          <el-button size="small" @click="updateProfileDialogVisible = false">取 消</el-button>
        </span>
      </el-dialog>

      <!-- 添加账户 -->
      <el-dialog
        title="添加教师"
        :visible.sync="createDialogVisible"
        destroy-on-close
      >
        <div style="color: red;margin-bottom: 20px">* 新账户默认密码为<strong>654321</strong>，创建账户后请修改</div>
        <v-teacher-add-update ref="AddDialog"/>
        <span slot="footer">
          <el-button type="primary" size="small" @click="createTeacher">创 建</el-button>
          <el-button size="small" @click="createDialogVisible = false">取 消</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import FileSaver from 'file-saver';
import XLSX from 'xlsx';

export default {
  name: "teacher",
  components: {
    'v-teacher-add-update': () => import('./teacher_add_update')
  },
  data() {
    return {
      mobile: '',
      email: '',
      enable: '',
      teacherList: [],
      mobileList: [],
      emailList: [],
      loading: true,
      pageNum: 1,
      pageSize: 10,
      total: 0,
      currentOperationIndex: 0,
      // 改密
      updatePasswordDialogVisible: false,
      updatePasswordDialogTitle: '',
      newPassword: '',
      // 修改
      updateProfileDialogVisible: false,
      updateProfileDialogTitle: '',
      //添加账户
      createDialogVisible: false

    }
  }, methods: {
    setIndexAndGetListData(index) {
      this.currentOperationIndex = index
      return this.teacherList[this.currentOperationIndex]
    },
    resetSearch(formName) {
      this.$refs[formName].resetFields();
      this.mobile = '';
      this.email = '';
      this.enable = '';
      this.getTeacherList();
    },
    btnQuery() {
      this.pageNum = 1;
      this.getTeacherList();
    },
    //分页大小改变
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.getTeacherList();
    },
    //当前页数改变
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum;
      this.getTeacherList();
    },
    //查询列表
    getTeacherList() {
      let jwtToken = localStorage.getItem('jwtToken');
      axios.get('/api/teacher/teacherList',
        {
          params: {
            mobile: this.mobile,
            email: this.email,
            enable: this.enable,
            pageNum: this.pageNum,
            pageSize: this.pageSize
          },
          headers: {jwtToken: jwtToken}
        }).then(result => {
        if (result.data.code === 200) {
          this.teacherList = result.data.data.teacherListVoList;
          this.pageNum = result.data.data.pageNum;
          this.pageSize = result.data.data.pageSize;
          this.total = result.data.data.total;
          this.loading = false;
        }
      }).catch(e => {
        this.$message({
          showClose: true,
          message: '服务器去火星了!',
          type: 'error',
          duration: 2000
        });
      })
    },
    //手机号远程搜索建议
    mobileFetch(queryString, cb) {
      var list = this.mobileList;
      var results = queryString ? list.filter(this.createMobileFilter(queryString)) : list;
      cb(results);
    },
    createMobileFilter(queryString) {
      return (mobile) => {
        return (mobile.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      }
    },
    queryMobile() {
      let jwtToken = localStorage.getItem('jwtToken');
      axios.get('/api/teacher/mobileList', {params: {}, headers: {jwtToken: jwtToken}})
        .then(result => {
          if (result.data.code === 200) {
            for (let item of result.data.data) {
              this.mobileList.push({"value": item.mobile});
            }
          }
        }).catch(e => {
        this.$message({
          showClose: true,
          message: '服务器去火星了!',
          type: 'error',
          duration: 2000
        });
      })
    },
    //邮箱远程搜索建议
    EmailFetch(queryString, cb) {
      var list = this.emailList;
      var results = queryString ? list.filter(this.createEmailFilter(queryString)) : list;
      cb(results);
    },
    createEmailFilter(queryString) {
      return (email) => {
        return (email.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      }
    },
    queryEmail() {
      let jwtToken = localStorage.getItem('jwtToken');
      axios.get('/api/teacher/emailList', {params: {}, headers: {jwtToken: jwtToken}})
        .then(result => {
          if (result.data.code === 200) {
            for (let item of result.data.data) {
              this.emailList.push({"value": item.email});
            }
          }
        }).catch(e => {
        this.$message({
          showClose: true,
          message: '服务器去火星了!',
          type: 'error',
          duration: 2000
        });
      })
    },
    //禁用按钮查询权限
    disableAuthority(index) {
      let jwtToken = localStorage.getItem('jwtToken')
      axios.get('/api/teacher/showDisableAuthority', {params: {}, headers: {jwtToken: jwtToken}})
        .then(result => {
          console.log(result.data);
          if (result.data.code === 200) {
            this.disableUser(index);
          } else {
            this.$message({
              showClose: true,
              message: result.data.msg,
              type: 'warning',
              duration: 2000
            });
          }
        }).catch(e => {
        this.$message({
          showClose: true,
          message: '服务器去火星了!',
          type: 'error',
          duration: 2000
        });
      })
    },
    //禁用
    disableUser(index) {
      const teacher = this.setIndexAndGetListData(index);
      let jwtToken = localStorage.getItem('jwtToken');
      axios.get('/api/teacher/disable', {params: {id: teacher.id}, headers: {jwtToken: jwtToken}})
        .then(result => {
          if (result.data.code === 200) {
            if (result.data.data > 0) {
              this.$message({
                showClose: true,
                message: '禁用成功！',
                type: 'success',
                duration: 2000
              });
            } else {
              this.$message({
                showClose: true,
                message: '请勿重复禁用！',
                type: 'warning',
                duration: 2000
              });
            }
            this.getTeacherList();
          }
        }).catch(e => {
        this.$message({
          showClose: true,
          message: '服务器去火星了!',
          type: 'error',
          duration: 2000
        });
      })
    },
    //启用按钮查询权限
    enableAuthority(index) {
      let jwtToken = localStorage.getItem('jwtToken')
      axios.get('/api/teacher/showEnableAuthority', {params: {}, headers: {jwtToken: jwtToken}})
        .then(result => {
          console.log(result.data);
          if (result.data.code === 200) {
            this.enableUser(index);
          } else {
            this.$message({
              showClose: true,
              message: result.data.msg,
              type: 'warning',
              duration: 2000
            });
          }
        }).catch(e => {
        this.$message({
          showClose: true,
          message: '服务器去火星了!',
          type: 'error',
          duration: 2000
        });
      })
    },
    //启用
    enableUser(index) {
      const teacher = this.setIndexAndGetListData(index);
      let jwtToken = localStorage.getItem('jwtToken');
      axios.get('/api/teacher/enable', {params: {id: teacher.id}, headers: {jwtToken: jwtToken}})
        .then(result => {
          if (result.data.code === 200) {
            if (result.data.data > 0) {
              this.$message({
                showClose: true,
                message: '启用成功！',
                type: 'success',
                duration: 2000
              });
            } else {
              this.$message({
                showClose: true,
                message: '请勿重复启用！',
                type: 'warning',
                duration: 2000
              });
            }
            this.getTeacherList();
          }
        }).catch(e => {
        this.$message({
          showClose: true,
          message: '服务器去火星了!',
          type: 'error',
          duration: 2000
        });
      })
    },
    openUpdatePasswordDialog(index) {
      this.updatePasswordDialogVisible = true
      const teacher = this.setIndexAndGetListData(index)
      this.updatePasswordDialogTitle = `更改教师[${teacher.name}]密码`
    },
    //改密按钮查询权限
    passwordAuthority(index) {
      let jwtToken = localStorage.getItem('jwtToken')
      axios.get('/api/teacher/showUpdatePasswordAuthority', {params: {}, headers: {jwtToken: jwtToken}})
        .then(result => {
          console.log(result.data);
          if (result.data.code === 200) {
            this.openUpdatePasswordDialog(index);
          } else {
            this.$message({
              showClose: true,
              message: result.data.msg,
              type: 'warning',
              duration: 2000
            });
          }
        }).catch(e => {
        this.$message({
          showClose: true,
          message: '服务器去火星了!',
          type: 'error',
          duration: 2000
        });
      })
    },
    //修改密码
    updatePassword() {
      const teacher = this.teacherList[this.currentOperationIndex]
      const params = {id: teacher.id, newPassword: this.newPassword}
      let jwtToken = localStorage.getItem('jwtToken');
      axios.get('/api/teacher/updatePassword', {params: params, headers: {jwtToken: jwtToken}})
        .then(result => {
          if (result.data.code === 200) {
            this.$message({
              showClose: true,
              message: '修改成功！',
              type: 'success',
              duration: 2000
            });
            this.updatePasswordDialogVisible = false
          } else {
            this.$message({
              showClose: true,
              message: '修改失败！',
              type: 'warning',
              duration: 2000
            });
          }
        }).catch(e => {
        this.$message({
          showClose: true,
          message: '服务器去火星了!',
          type: 'error',
          duration: 2000
        });
      })
    },
    openUpdateProfileDialog(index) {
      this.updateProfileDialogVisible = true
      const teacher = this.setIndexAndGetListData(index)
      this.updateProfileDialogTitle = `更改教师[${teacher.name}]信息`
      setTimeout(function () {
        this.$refs.UpdateDialog.setData(teacher)
      }.bind(this), 200)
    },
    //修改按钮查询权限
    updateAuthority() {
      let jwtToken = localStorage.getItem('jwtToken')
      axios.get('/api/teacher/showUpdateProfileAuthority', {params: {}, headers: {jwtToken: jwtToken}})
        .then(result => {
          console.log(result.data);
          if (result.data.code === 200) {
            this.updateProfile();
          } else {
            this.$message({
              showClose: true,
              message: result.data.msg,
              type: 'warning',
              duration: 2000
            });
          }
        }).catch(e => {
        this.$message({
          showClose: true,
          message: '服务器去火星了!',
          type: 'error',
          duration: 2000
        });
      })
    },
    //修改信息
    updateProfile() {
      const teacher = this.$refs.UpdateDialog.getData()
      let jwtToken = localStorage.getItem('jwtToken')
      axios.post('/api/teacher/updateProfile', teacher,
        {params: {}, headers: {jwtToken: jwtToken}}).then(result => {
        if (result.data.code === 200) {
          this.$message({
            showClose: true,
            message: '修改成功！',
            type: 'success',
            duration: 2000
          });
          this.updateProfileDialogVisible = false
        } else {
          this.$message({
            showClose: true,
            message: '修改失败！',
            type: 'warning',
            duration: 2000
          });
        }
        this.getTeacherList();
      }).catch(e => {
        this.$message({
          showClose: true,
          message: '服务器去火星了!',
          type: 'error',
          duration: 2000
        });
      })
    },
    //添加按钮查询权限
    addAuthority() {
      let jwtToken = localStorage.getItem('jwtToken')
      axios.get('/api/teacher/showAddAuthority', {params: {}, headers: {jwtToken: jwtToken}})
        .then(result => {
          console.log(result.data);
          if (result.data.code === 200) {
            this.createDialogVisible=true;
          } else {
            this.$message({
              showClose: true,
              message: result.data.msg,
              type: 'warning',
              duration: 2000
            });
          }
        }).catch(e => {
        this.$message({
          showClose: true,
          message: '服务器去火星了!',
          type: 'error',
          duration: 2000
        });
      })
    },
    //添加教师
    createTeacher() {
      const teacher = this.$refs.AddDialog.getData()
      teacher.password = '654321'
      teacher.status = 2
      teacher.enable = 1
      let jwtToken = localStorage.getItem('jwtToken')
      axios.post('/api/teacher/add', teacher,
        {params: {}, headers: {jwtToken: jwtToken}}).then(result => {
        if (result.data.code === 200) {
          this.$message({
            showClose: true,
            message: '添加成功！',
            type: 'success',
            duration: 2000
          });
          this.createDialogVisible = false
        } else {
          this.$message({
            showClose: true,
            message: '修改失败！',
            type: 'warning',
            duration: 2000
          });
        }
        this.getTeacherList();
      }).catch(e => {
        this.$message({
          showClose: true,
          message: '服务器去火星了!',
          type: 'error',
          duration: 2000
        });
      })
    },
    //导出Excel
    exportToExcel() {
      //获取 table 表格数据
      let xlsxParam = {raw: true}
      let et = XLSX.utils.table_to_book(document.querySelector('#teacherTable'), xlsxParam); //此处传入table的DOM节点
      let etout = XLSX.write(et, {
        bookType: 'xlsx',
        bookSST: true,
        type: 'array'
      });
      try {
        FileSaver.saveAs(new Blob([etout], {
          type: 'application/octet-stream'
        }), 'studentList.xlsx');   //trade-publish.xlsx 为导出的文件名
      } catch (e) {
        console.log(e, etout);
      }
      return etout;
    }
  },
  created() {
    this.getTeacherList();
    this.queryMobile();
    this.queryEmail();
  }
}
</script>

<style scoped>

</style>
